<?php
/** 
 * route the url to currect controller is my responsibility
 * @author Leo Ning <leo.ning@like18.com>
 */
class Router {
	private static $routes = array ();
	private static $aroutes = array ();
	/**
	 * 
	 * 设置路由规则
	 * @param string $pattern 
	 * @param array $dest
	 * @param boolean $after 是否是后置路由
	 */
	public static function route($pattern, $dest, $after = false) {
		if ($after) {
			self::$aroutes [$pattern] = $dest;
		} else {
			self::$routes [$pattern] = $dest;
		}
	}
	/**
	 * 是否有后置路由
	 * @return boolean 
	 */
	public static function hasAfterRoutes() {
		return ! empty ( self::$aroutes );
	}
	/**
	 * 
	 * 得到请求目的地信息
	 * @param string $url
	 * @param boolean $after
	 * @return array
	 */
	public static function getRoute($url, $after = false) {
		$dest = array ();
		$routes = $after ? self::$aroutes : self::$routes;
		foreach ( $routes as $p => $d ) {
			if (@preg_match ( $p, $url )) {
				$dest = $d;
				if (isset ( $d ['last'] ) && $d ['last']) {
					break;
				}
			}
		}
		$dest = apply_filter ( 'after_route', $dest, $url );
		if (empty ( $dest )) {
			$dest = array ('module' => 'default', 'action' => "index", 'params' => array () );
			$sems = explode ( "/", trim ( $url, '/' ) );
			
			if (count ( $sems ) > 0) {
				$dest ['module'] = array_shift ( $sems );
			}
			
			if (count ( $sems ) > 0) {
				$dest ['action'] = array_shift ( $sems );
			}
			
			if (count ( $sems ) > 0) {
				$dest ['params'] = $sems;
			}
		} else if (! isset ( $dest ['params'] )) {
			$ma = '/' . (isset ( $dest ['plugin'] ) ? $dest ['plugin'] : $dest ['module']) . '/' . $dest ['action'];
			$url = trim ( str_replace ( $ma, "", $url ), '/' );
			$params = array ();
			if (! empty ( $url )) {
				$params = explode ( "/", $url );
			}
			$dest ['params'] = $params;
		}
		return $dest;
	}
}